package com.atguigu.exam;

import java.io.*;
import java.util.ArrayList;

/**
 * （字符流）读取一个文本文件，每行都追加一个“好”，在文件结尾再追加“完毕”。
 *
 * @author xbd
 * @create 2021-05-30 23:57
 */
public class AddMessageTest {
    public static void main(String[] args) {
        //文件对象
        File file = new File("a.txt");
        //字符缓冲流
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        //存储读取的内容
        ArrayList<String> arrayList = new ArrayList<>();
        try {
            //打开输入流
            bufferedReader = new BufferedReader(new FileReader(file));
            //存储读取内容
            String content = "";
            //读取数据
            while ((content = bufferedReader.readLine()) != null) {
                System.out.println(content);
                //每行都追加一个“好”
                content += "好";
                //把内容存入arrayList
                arrayList.add(content);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            //打开输出流
            bufferedWriter = new BufferedWriter(new FileWriter(file));
            //遍历arrayList
            for (int i = 0; i < arrayList.size(); i++) {
                //判断是不是最后一行
                if (i == arrayList.size() - 1) {
                    //写数据
                    bufferedWriter.write(arrayList.get(i));
                    //刷新
                    bufferedWriter.flush();
                } else {
                    //写数据
                    bufferedWriter.write(arrayList.get(i));
                    //换行
                    bufferedWriter.newLine();
                    //刷新
                    bufferedWriter.flush();
                }
            }
            //在文件结尾再追加“完毕”
            bufferedWriter.write("完毕");
            //刷新文件
            bufferedWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
